﻿


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;



namespace MisureCelleCarico
{
    
    public partial class Form1 : Form
    {
        public const  byte      SYNC            = 0xAA;
        public const  byte      DOWNLOAD        = 0x11;
        public const  byte      POLL            = 0x10;
        public const  byte      GET_RELEASE     = 0x80;
        public const  byte	    CHECKSUM	    = 0x5B;
        public const  byte      SET_FLASH       = 0x19;
        public const  byte      CLEAR_FLASH     = 0x18;
        public const  byte      SET_SAMPLING    = 0x41;

        public Form1()
        {
            InitializeComponent();
            buf1 = new byte[256];
            memFlash = new byte[128*1024];
            numeroPagine = 0;
            mLineeSalvate = 0;
            
        }

        /// <summary>
        ///  propeties
        /// </summary>
        int m_connectStuts = -1;
        byte[] buf1;                    /// local buffer
        byte[] memFlash;                /// image of flash
        int numeroPagine, m_pagLette;
        int mLineeSalvate;              /// linee fin'ora salvate


        /// <summary>
        /// Connect to serial port and try what is available
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            string nome;
            int statoPorta = -1;
            int val = -1;
            string[] ports = SerialPort.GetPortNames();      
            if (m_connectStuts != 0)
                /// not connected: we try to connect to
            {
                if (ports.Length != 0)
                {
                    for (int i = 0; i < ports.Length; i++)
                    {
                        /// prova le porte una per una
                        nome = ports[i];
                        serialPort1.PortName = nome;
                        serialPort1.BaudRate = 115200;
                        serialPort1.ReadTimeout = 500;
                        try
                        {

                            /// prova ad aprire la porta
                            serialPort1.Open();
                            statoPorta = 0;
                        }

                        catch (SystemException sE)
                        {
                            /// la porta non esiste
                            Console.WriteLine(sE.Message);
                        }


                        /// write on port
                        if (statoPorta == 0)
                        {
                            val = chiama();
                            if (val == 0)
                                i = ports.Length + 1;
                            if (val == -2)
                            {
                                serialPort1.Close();
                                statoPorta = -1;
                            }
                        }
                    }
                    if (val == 0)
                    {
                        label1.Text = "Connected to MCU";
                        m_connectStuts = 0;
                        button2.Enabled = true;
                        button3.Enabled = true;
                        button5.Enabled = true;
                        //button6.Enabled = true;
                        button7.Enabled = true;
                        Console.WriteLine("Connesso MCU");
                    }
                    else
                    {
                        label1.Text = "MCU not found";
                        m_connectStuts = -1;
                        button2.Enabled = false;
                        button3.Enabled = false;
                        button5.Enabled = false;
                        //button6.Enabled = false;
                        button7.Enabled = false;
                    }
                    if (statoPorta == 0 && val != 0)
                        serialPort1.Close();
                }
            }
        }

        /// <summary>
        /// Write a string on serial port and wait reply
        /// </summary>
        int chiama() {
            int i;
            byte v;
            byte[] buf = new byte[16];
            byte[] str = new byte[16];
            str[0] = SYNC;
            str[1] = POLL;
            serialPort1.Write(str, 0, 2);
            buf[0] = 0;
            for (i = 0; i < 2; i++)
                buf[0] +=str[i];
            //serialPort1.Write(Convert.ToString(v));
            //v += Convert.ToByte('S');
            //serialPort1.Write(Convert.ToString(v));
            //v += Convert.ToByte('P');
            //serialPort1.Write(Convert.ToString(v));
            /// compute checksum
            buf[0] ^= CHECKSUM;
            /// and send it
            serialPort1.Write(buf, 0, 1);
            i = 0;
            do{
                try
                {
                    serialPort1.Read(buf, i, 1);
                    //serialPort1.Read(buf, 1, 1);
                    i++;
                }
                catch (System.Exception sE)
                {
                    Console.WriteLine(sE);
                    return -2;
                }
            }
            while(serialPort1.BytesToRead > 0);
            v = buf[0];
            v ^= CHECKSUM;
            if (buf[0] == POLL && v == buf[1]){
            /// we had also received the version of SW
            /// 
                v = 0;
                for (int j = 2; j < 9; j++)
                    v += buf[j];
                v ^= CHECKSUM;
                if (v == buf[9]) { 
                /// ok, stampo il codice
                /// 
                    string s="";
                    for (int j = 2; j < 9; j++)
                        s += Convert.ToString(Convert.ToChar(buf[j]));
                    label3.Text += s;
                    
                
                }

                return 0;
            
            }
                
            else return -1;       
        }

        /// <summary>
        /// Donwload the data from the I2C eeprom on the board
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            int i;
            byte v;
            byte[] buf1 = new byte[256];
            byte[] str = new byte[4];

            if (m_connectStuts != 0)
                return;
            /// imposto le pagine gia' lette
            m_pagLette = numeroPagine;
            bool fineCiclo = false;
            for (int contatorePagine = m_pagLette;
                (contatorePagine < 128 + m_pagLette) && (fineCiclo == false); 
                contatorePagine++)
            {
                str[0] = SYNC;
                str[1] = DOWNLOAD;
                serialPort1.Write(str, 0, 2);
                buf1[0] = 0;
                for (i = 0; i < 2; i++)
                    buf1[0] += str[i];
                //serialPort1.Write(Convert.ToString(v));
                //v += Convert.ToByte('S');
                //serialPort1.Write(Convert.ToString(v));
                //v += Convert.ToByte('P');
                //serialPort1.Write(Convert.ToString(v));
                /// compute checksum
                buf1[0] ^= CHECKSUM;
                /// and send it
                serialPort1.Write(buf1, 0, 1);
                i = 0;
                v = 0;
                do
                {
                    try
                    {
                        serialPort1.Read(buf1, i, 1);                      
                        i++;
                    }
                    catch (System.Exception sE)
                    {
                        Console.WriteLine(sE);
                        return;
                    }
                }
                while (i < 2);
                v = buf1[0];
                v^= CHECKSUM;
                if (buf1[0] == DOWNLOAD && v == buf1[1])
                {
                /// ok, the command's echo is arrived
                /// I may read all flash...1024 pages
                /// 
                
                    /// we pass all pages on the flash memory
                    i = 0;
                    v = 0;
                    do
                    {
                        try
                        {
                            serialPort1.Read(buf1, i, 1);
                            //serialPort1.Read(buf, 1, 1);
                            //v += buf1[i];
                            i++;
                        }
                        catch (System.Exception sE)
                        {
                            Console.WriteLine(sE);
                            return;
                        }
                    }
                    while (i < 129);
                    for (int j = 0; j < i - 1; j++)
                        v += buf1[j];
                    v ^= CHECKSUM;
                    if (v == buf1[i - 1])
                    {
                        /// this block is ok.
                        /// 
                        Console.WriteLine("block {0}  ok", contatorePagine);
                        string s = "";
                        int sommaControllo = 0;
                        for (i = 0; i < 128; i++)
                        {
                            sommaControllo += buf1[i];
                            s += "\t" + Convert.ToString(buf1[i]);
                            /// copy of a page
                            memFlash[contatorePagine * 128 + i] = buf1[i];
                            /// aggiorno il numero di pagine gia' lette
                            numeroPagine = contatorePagine;

                        }
                        richTextBox1.Text += s + "\n";
                        if (sommaControllo == 255 * 128) {
                            fineCiclo = true;
                        }

                    }

                }
                /// we finished to read all flash content
                /// we can write data on a file or copy the rich box contents on excel
                
            }
        }

        /// <summary>
        /// Disconnect to port
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            if (m_connectStuts == 0){
                /// alreay connect: we can disconnect
                /// 
                m_connectStuts = -1;
                serialPort1.Close();
                label1.Text = "Not connected";
                button2.Enabled = false;
                button3.Enabled = false;
                button5.Enabled = false;
                button7.Enabled = false;
                Console.WriteLine("Disconnessa MCU");
                label3.Text = "";
            }
           

        }

        /// <summary>
        /// imposta la flash a 255
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            int i;
            byte v;
            byte[] buf = new byte[2];
            byte[] str = new byte[4];
            str[0] = SYNC;
            str[1] = SET_FLASH;
            serialPort1.Write(str, 0, 2);
            buf[0] = 0;
            for (i = 0; i < 2; i++)
                buf[0] += str[i];
            //serialPort1.Write(Convert.ToString(v));
            //v += Convert.ToByte('S');
            //serialPort1.Write(Convert.ToString(v));
            //v += Convert.ToByte('P');
            //serialPort1.Write(Convert.ToString(v));
            /// compute checksum
            buf[0] ^= CHECKSUM;
            /// and send it
            serialPort1.Write(buf, 0, 1);
            i = 0;
            do
            {
                try
                {
                    serialPort1.Read(buf, i, 1);
                    //serialPort1.Read(buf, 1, 1);
                    i++;
                }
                catch (System.Exception sE)
                {
                    Console.WriteLine(sE);
                    return ;
                }
            }
            while (serialPort1.BytesToRead > 0);
            v = buf[0];
            v ^= CHECKSUM;
            if (buf[0] == SET_FLASH && v == buf[1])
            {
                Console.WriteLine("ricevuto set flash");
                return;
            }

            else
            {
                Console.WriteLine("set non ricevuto ");
                return;
            }       
        }

        /// <summary>
        /// clear the flash
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {
            int i;
            byte v;
            byte[] buf = new byte[2];
            byte[] str = new byte[4];
            str[0] = SYNC;
            str[1] = CLEAR_FLASH;
            serialPort1.Write(str, 0, 2);
            buf[0] = 0;
            for (i = 0; i < 2; i++)
                buf[0] += str[i];
            //serialPort1.Write(Convert.ToString(v));
            //v += Convert.ToByte('S');
            //serialPort1.Write(Convert.ToString(v));
            //v += Convert.ToByte('P');
            //serialPort1.Write(Convert.ToString(v));
            /// compute checksum
            buf[0] ^= CHECKSUM;
            /// and send it
            serialPort1.Write(buf, 0, 1);
            i = 0;
            do
            {
                try
                {
                    serialPort1.Read(buf, i, 1);
                    //serialPort1.Read(buf, 1, 1);
                    i++;
                }
                catch (System.Exception sE)
                {
                    Console.WriteLine(sE);
                    return ;
                }
            }
            while (serialPort1.BytesToRead > 0);
            v = buf[0];
            v ^= CHECKSUM;
            if (buf[0] == CLEAR_FLASH && v == buf[1])
            {
                Console.WriteLine("ricevuto reset flash");
                return;
            }
            else{
                Console.WriteLine("reset non ricevuto");
                return;       
            }
        
        }

        /// <summary>
        /// save a data file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            byte [] buffer = new byte [3];
            char [] carattere = new char[128];
            byte[] buf1 = new byte[10];
            UTF8Encoding utf8 = new UTF8Encoding();
            Stream myStream;
            //buffer[0] = Convert.ToByte('A');
            //buffer = new UTF8Encoding(true).GetBytes("pippo");
            saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                
                myStream = saveFileDialog1.OpenFile();
                
                for (int np = 0; np < numeroPagine; np++)
                    /// page byte
                    for (int i = 0; i < 128; i++) {
                        //string s = Convert.ToString(memFlash[i]);
                        buf1 = utf8.GetBytes(Convert.ToString(memFlash[np * 128 + i]));
                        myStream.Write(buf1, 0, buf1.Length);
                        /// va a capo ogni riga.
                        /// arrivati a 10000 linee va a capo
                        
                        string s1 = "\n";
                        buffer = utf8.GetBytes(s1);
                        myStream.Write(buffer, 0, buffer.Length);
                        mLineeSalvate++;
                        if (mLineeSalvate > 10000) {
                            mLineeSalvate = 0;

                        }
                    }               
                myStream.Close();
            }
        }

        /// <summary>
        ///  clear the contents of rich boxtext
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = "";
            numeroPagine = 0;
            m_pagLette = 0;

        }

        /// <summary>
        /// set the sampling time on the board
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button7_Click(object sender, EventArgs e)
        {
            byte[] buf = new byte[3];
            byte[] str = new byte[4];
            buf[0] = SYNC;
            buf[1] = SET_SAMPLING;
            buf[2] = buf[0];
            buf[2] += buf[1];
            buf[2] ^= CHECKSUM;
            try
            {
                serialPort1.Write(buf, 0, 3);
            }
            catch (System.Exception s) {
                Console.WriteLine(s.Message);
            }

            /// trasmissione dato
            /// 
            try
            {
                buf[0] = Convert.ToByte(textBox1.Text);
            }
            catch (System.Exception s)
            {
                buf[0] = 255;
                textBox1.Text = "255";
            }
            buf[1] = CHECKSUM;
            buf[1] ^= buf[0];

            try
            {
                serialPort1.Write(buf, 0, 2);
            }
            catch (System.Exception s)
            {
                Console.WriteLine(s.Message);
            }

        }
    }
}
